<?php
session_start();
date_default_timezone_set('PRC');

/**
 * 执行sqlite增删改查
 * @param  字符串 $query 执行语句
 * @return 复合        查询的场合返回集合，增删改的场合返回true/false
 */
function go_sqlite($query) {
	global $CFG, $sqlite_link;

	caozq_print_sql_to_file($query);

	if(!$sqlite_link) {
		$sqlite_link = new PDO($CFG->dbhost);
		global $sqlite_link;
	}

	$result = $sqlite_link->query($query);
	if ($result) {
		return $result;
	} else {
		throw new Exception("Database Error:{$query}", 1);
	}
}
// save_upload_file 保存上传的单文件
// $input_name input[type="file"]框的name属性值
// $to_dir 需要保存到的目录
// $to_file_fullpath 保存的文件的完整的路径
function save_upload_file($input_name, $to_dir, $to_file_fullpath) {
	$ret = false;
	if (!file_exists($to_dir)) {
		mkdir($to_dir, "0777", true);
	}
	if (!empty($_FILES[$input_name]) && !empty($_FILES[$input_name]['size'])) {
		$ret = move_uploaded_file($_FILES[$input_name]["tmp_name"], $to_file_fullpath);
	}
	return $ret;
}
function caozq_print_sql_to_file($sql) {
	global $CFG;
	if (!empty($CFG->sqldebug) && !empty($CFG->sqllogdir)) {
		$dir_path = $CFG->sqllogdir;
		$outline = "[".date("H:i:s")."]".$sql."\n";
		if (!file_exists($dir_path)) {
			mkdir($dir_path, "0777", true);
		}
		$fp = fopen($dir_path."box_sqlite_log_".date("Y-m-d").".txt", "a");
		if(!$fp){
			// echo "文件打开失败！";
		}else{
			fwrite($fp, $outline);
		}
		fclose($fp);
	}
}
function get_record_sql($query, $strict = false) {
	$ret = false;
	if ($result = go_sqlite($query)) {
		$result->setFetchMode(PDO::FETCH_OBJ);
		while ($obj = $result->fetch()) {
			$ret = $obj;
			break;
		}
	}
	if ($strict && !$ret) {
		throw new Exception("Error Processing Request:Data is not right", 1);
	}
	return $ret;
}
function get_records_sql($query, $strict = false) {
	$ret = false;
	if ($result = go_sqlite($query)) {
		$result->setFetchMode(PDO::FETCH_OBJ);
		$ret = $result->fetchAll();
	}
	if ($strict && !$ret) {
		throw new Exception("Error Processing Request:Data is not right", 1);
	}
	return $ret;
}
function get_array_sql($query, $strict = false) {
	$ret = false;
	if ($result = go_sqlite($query)) {
		$result->setFetchMode(PDO::FETCH_ASSOC);
		while ($arr = $result->fetch()) {
			$ret = $arr;
			break;
		}
	}
	if ($strict && !$ret) {
		throw new Exception("Error Processing Request:Data is not right", 1);
	}
	return $ret;
}
function get_arrays_sql($query, $strict = false) {
	$ret = false;
	if ($result = go_sqlite($query)) {
		$result->setFetchMode(PDO::FETCH_ASSOC);
		$ret = $result->fetchAll();
	}
	if ($strict && !$ret) {
		throw new Exception("Error Processing Request:Data is not right", 1);
	}
	return $ret;
}
/**
 * [insert 新增数据]
 * @param  [字符串]  $table_name [表名]
 * @param  array   $arr        [新增数据]
 * @param  boolean $isReturnId [是否返回ID]
 * @return [复合类型]              [返回ID的场合返回ID，不返回ID的场合返回true和false]
 */
function insert($table_name, array $arr, $isReturnId = false) {
	global $sqlite_link;
	$keys   = array();
	$values = array();
	foreach ($arr as $key => $value) {
		$keys[]   = $key;
		$values[] = "'".sqlite_str_format($value)."'";
	}
	$sql = "INSERT INTO {$table_name} (".implode(",", $keys).") VALUES (".implode(",", $values).")";
	if ($result = go_sqlite($sql)) {
		if ($isReturnId) {
			$id = $sqlite_link->lastInsertId();
			return $id;
		} else {
			return true;
		}
	} else {
		return false;
	}
}
/**
 * [update 更新数据]
 * @param  [字符串] $table_name [表名]
 * @param  array  $arr        [要更新的字段]
 * @param  array  $where      [检索条件]
 * @return [布尔值]             [true/false]
 */
function update($table_name, array $arr, array $where) {
	$values = array();
	$wheres = array();
	foreach ($arr as $key => $value) {
		$values[] = $key." = '".sqlite_str_format($value)."'";
	}
	foreach ($where as $key => $value) {
		$wheres[] = $key." = '".sqlite_str_format($value)."'";
	}
	$sql = "UPDATE {$table_name} SET ".implode(",", $values)." WHERE ".implode(" AND ", $wheres);
	$result = go_sqlite($sql);
	if ($result) {
		return true;
	} else {
		return false;
	}
}
/**
 * INSERT的场合，需要进行特殊字符处理
 */
function sqlite_str_format($str) {
	$str = str_replace("'", "''", $str);
	return $str;
}
function print_j($param) {
	print_r(json_encode($param));
}
function get_option_value($key, $defaultval) {
	$ret = "";
	if(isset($_POST[$key])){
		$ret = $_POST[$key];
	}
	if($ret == "") {
		if(isset($_GET[$key])){
			$ret = $_GET[$key];
		}
	}
	if($ret == null || $ret == "") {
		$ret = $defaultval;
	}
	return $ret;
}
function get_require_value($key) {
	$ret = "";
	if(isset($_POST[$key])){
		$ret = $_POST[$key];
	}
	if($ret == "") {
		if(isset($_GET[$key])){
			$ret = $_GET[$key];
		}
	}
	if($ret == null || $ret == "") {
		throw new Exception("Error {$key} not find in (get or post)!");
	}
	return $ret;
}
function redirect($url) {
	header("Location: {$url}");
}
function rn_to_br($str) {
	$str = str_replace("\r\n", "<br/>", $str);
	$str = str_replace("\n", "<br/>", $str);
	$str = str_replace(" ", "&nbsp;", $str);
	return $str;
}
/**
 * [get_cate_nav description]
 * @param  [type]  $cateid [description]
 * @param  [type]  $cache  [0:note view index 页面用 1：缓存页面用 2：新增分类页面用]
 * @return [type]          [description]
 */
function get_system_datetime() {
	$datetime = date("YmdHis",time());
	return $datetime;
}
function get_system_datetime_format($str) {
	$ret = "";
	$ret .= substr($str, 0, 4)."-";
	$ret .= substr($str, 4, 2)."-";
	$ret .= substr($str, 6, 2)." ";
	$ret .= substr($str, 8, 2).":";
	$ret .= substr($str, 10, 2).":";
	$ret .= substr($str, 12, 2);
	return $ret;
}
function convert_to_utf8($str) {
	$fromEncodeArr = array("GB2312", "GBK", "ASCII");
	$toEncode = "UTF-8";
	$str = mb_convert_encoding($str, $toEncode, $fromEncodeArr);
	return $str;
}
function check_wap() {
    $user_agent = $_SERVER['HTTP_USER_AGENT']; 
    $mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte"); 
    $is_mobile = false; 
    foreach ($mobile_agents as $device) { 
        if (stristr($user_agent, $device)) { 
            $is_mobile = true; 
            break; 
        }
    }
    return $is_mobile; 
}
/** 获取当前时间戳，精确到毫秒 */
function microtime_float() {
	list($usec, $sec) = explode(" ", microtime());
	return ((float)$usec + (float)$sec);
}

/** 格式化时间戳，精确到毫秒，x代表毫秒 */
function microtime_format($tag, $time) {
	list($usec, $sec) = explode(".", $time);
	$date = date($tag,$usec);
	return str_replace('x', $sec, $date);
}
// 本项目
function page_url_add($url, $name) {
	global $CFG;
	$CFG->pageurl[] = array("url" => $url, "name" => $name);
}